"""
---------------------------------------------------------------------
- File: security.py
- Date: 2025/7/10
- Author: yangzhide
- Email: xxzjyzd@126.com
- Description: 安全相关（JWT、密码哈希）
---------------------------------------------------------------------
"""

from datetime import datetime, timedelta, timezone

import jwt
from passlib.context import CryptContext

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e89999"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 3  # 3分钟


def get_password_hash(password):
    """密码哈希"""
    return pwd_context.hash(password)


def verify_password(plain_password, hashed_password):
    """验证哈希密码"""
    return pwd_context.verify(plain_password, hashed_password)


def create_access_token(data: dict, expires_delta: timedelta | None = None):
    """创建成功token"""
    to_encode = data.copy()
    if expires_delta:
        expire = datetime.now(timezone.utc) + expires_delta
    else:
        expire = datetime.now(timezone.utc) + timedelta(minutes=15)

    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
    return encoded_jwt
